//导入Ajax
import {
    ajax,
    isObject
} from "./ajax.js"
//导入放大镜
import Magnifier from "./magnifier.js"
var bname = unescape(window.location.href.split("?")[1].split("=")[1].split('#')[0])
// 作者名字
var shop =""
//历史记录数组
var harr =[];
var getCookie = function getCookie(key) {
    var arr1 = document.cookie.split('; ')
    //["user1=111asdasd", "user2=222gfhft", "user3=333wwwaa"]
    for (var i = 0; i < arr1.length; i++) {
        var arr2 = arr1[i].split('=') //['user1','111asdasd']
        if (arr2[0] === key) {
            // 对数据进行解码并返回
            return unescape(arr2[1])
        }
    }
    return null
}
new Promise(function(resolve, reject){
//调用ajax,进行初始化渲染*************************
ajax({
    url: "./php/search.php",
    dataType: "json",
    data: {ways:"detail",id:bname},
    type: "get",
    cache: false,
    //调用成功执行函数
    success: function (data) {
        shop = data[0]["shop"];
        if(localStorage.getItem("thinghistory")){
            var thistory = localStorage.getItem("thinghistory")
            harr = JSON.parse(thistory)
            if(harr.find(item=>{
                return item.id == data[0]['id']
            })){

            }else{
                harr.unshift(data[0])
            }
            if(harr.length>=10){
                harr.length=10
            }
            thistory = JSON.stringify(harr)
            //添加历史记录
            localStorage.setItem("thinghistory" , thistory)
        }else{
            var as = []
            as.push(data[0])
            thistory = JSON.stringify(as)
            localStorage.setItem("thinghistory" , thistory)
        }
        document.title = data[0]['goodsname']
        // 分类
        $(".include").html(`
                <span>${data[0]['bigNav']}</span>
                <span>&gt;</span>
                <span>${data[0]['midNav']}</span>
                <span>&gt;</span>
                <span>${data[0]['smaNav']}</span>
                `)

        // 放大镜图片
        $(".ori img")[0].src = data[0]['url']
        $(".large img")[0].src = data[0]['url']

        // 购物模板
        // 书名
        $(".bname h1").html(data[0]['goodsname'])
        // 定价
        $(".price-o b").html(data[0]['price1'])
        // 文轩价
        $(".price-n b").html(data[0]['price2'])
        // 作者
        $(".author a").html(data[0]['shop'])
        //所属分类
        $(".class dd").html(`
                <a href='#'>${data[0]['bigNav']}</a>
                > <a href='#'>${data[0]['midNav']}</a>
                > <a href='#'>${data[0]['smaNav']}</a>
                `)
        //书本信息
        $(".intro-cont ul").html(`
                <li>品 牌：<a href="#" >${data[0]['shop']}</a> </li>
                <li>适用：<a  href="#">${data[0]['bigNav']}</a></li>
                <li>种类：${data[0]['midNav']}</li>
                <li>品种：${data[0]['smaNav']}</li>
                <li>材质：${data[0]['mat']}</li>
                `)
                resolve()
    },
    error: function (x) {
        alert(x)
    }
})
//调用ajax,进行初始化渲染*************************
})
.then(()=>{
//调用ajax,获取该作者的所有书和历史记录*************************
ajax({
    url: "./php/search.php",
    dataType: "json",
    data: {ways:"shop",shop:shop},
    type: "get",
    cache: false,
    //调用成功执行函数
    success: function (data) {
        //该作者的其他商品
        var str = ""
        for(var i = 0;i<10;i++){
            str +=`
            <div class="ano-book">
            <div>
                <img src=${data[i]["url"]} alt="">
            </div>
            <p><a href="./detail.html?bname=${escape(data[i]['id'])}">${data[i]['goodsname']}</a></p>
            <span>木韵价:</span>
            <b>${data[i]["price2"]}</b>
            </div>
            `
        }
        $(".another-cont").html(str+`
        <div class="ano-more">
        <p><a href="#">更多&gt;&gt;</a></p>
        </div>
        `)
        //历史记录
        var str1 = "";
        for(var i = 0;i<harr.length;i++){
            if(i==0){
                str1 +=`
                <div class="det-book">
                <div>
                    <img src=${harr[i]["url"]} alt="">
                </div>
                <p><a href="./detail.html?bname=${escape(harr[i]['id'])}">${harr[i]['goodsname']}</a></p>
                <span>木韵价:</span>
                <b>${harr[i]["price2"]}</b>
                </div>
                `
            }else{
                str1 +=`
                <p class="det-p">
                <a href="./detail.html?bname=${escape(harr[i]['id'])}">* ${harr[i]['goodsname']}</a>
                </p>
                `
            }
        }
        $(".det-history-cont").html(str1)


    },
    error: function (x) {
        alert(x)
    }
})
//调用ajax,获取该作者的所有书和历史记录*************************
//调用ajax给对话按钮添加点击事件********************
// 获取cookie
$.post('./php/chat.php',{
    name:getCookie("username"),
    way:'talk',
    peoplename : shop
    },function(data){
        data=$.parseJSON( data )
        $('.toshop').on('click',function(){
            if(getCookie("username")&&getCookie("loginsucess")=="true"){
                if(data[0]&&data[1]){
                    $.post('./php/chat.php',{
                        useid:data[0],
                        way:'talk3',
                        peopleid : data[1]
                        },function(data){
                        });

                    $('.toshop').attr('href','./chat.html')
                    return true
                }else{
                    alert('请先登录')
                }
            }else{
                alert('请先登录')
            }
            return false
        })

    });
//调用ajax给对话按钮添加点击事件********************

})





// 实例放大镜
new Magnifier($(".ori")[0], $(".large")[0], $(".fil")[0])
//给回到顶部添加点击事件
$(".totop").on("click", function () {
    document.documentElement.scrollTop = 0
})
window.addEventListener("scroll", function () {
    if (document.documentElement.scrollTop >= 300) {
        $(".totop")[0].style.display = "block"
    } else {
        $(".totop")[0].style.display = "none"
    }
})

//添加购物车
$(".buy-active a").on("click",function(){
//要购买的数量
var n = $(".buy-num-text").val()
var carharr = []
if(localStorage.getItem("thingcarhistory")){
    var thistory = localStorage.getItem("thingcarhistory")
    carharr = JSON.parse(thistory)
    if(carharr.find(item=>{
        if(item.id == bname){
            item.id = bname;
            item.num = n;
        }
        return item.id == bname
    })){

    }else{
        var item ={}
        item.id = bname;
        item.num = n;
        carharr.push(item)
    }
    thistory = JSON.stringify(carharr)
    //添加历史记录
    localStorage.setItem("thingcarhistory" , thistory)
}else{
    var item ={}
    item.id = bname;
    item.num = n;
    carharr.push(item)
    thistory = JSON.stringify(carharr)
    localStorage.setItem("thingcarhistory" , thistory)
}
alert("已成功添加到购物车")
})

//改变购买数量
$(".reduce-btn").on("click",function(){
    if($(".buy-num-text").val()<=1){
        $(".buy-num-text").val(1)
        return
    }
    var a= parseInt($(".buy-num-text").val())-1
    $(".buy-num-text").val(a)
})
$(".add-btn").on("click",function(){
    var a= parseInt($(".buy-num-text").val())+1
    $(".buy-num-text").val(a)
})
//添加到收藏夹
$(".buy-active div").on("click",function(){
    $.post('./php/chat.php',{
        name:getCookie("username"),
        way:'addCollect',
        goodsid:bname
        },function(data){
            alert(data)
        });
})

//评价商品**************************************
var fen = "0"
$(".pi2 b").on("mouseenter",(e)=>{
    for(var i=0;i<$(".pi2 b").length;i++){
        if($(".pi2 b")[i].getAttribute("index")<=e.target.getAttribute("index")){
            $(".pi2 b")[i].innerHTML="★"
        }else{
            $(".pi2 b")[i].innerHTML="☆"
        }
    }
    fen=e.target.getAttribute("index")
})
$.post('./php/comment.php',{
    id:bname,
    way:'start',
    },function(data){
        if(!data){
            return
        }
        var data=JSON.parse(data)
        $(".intro-cont1 ul").html('')
        var str ="";
        for(var i=0;i<data.length;i++){
            var aa=`<div class="pi3">`
            for(var j=0;j<5;j++){
                if(j<=data[i].fen){
                    aa += `<b index='${j}'>★</b>`
                }else{
                    aa += `<b index='${j}'>☆</b>`
                }
            }
            aa += `</div>`
            str +=`
            <li>
            <div class="top1">
                <span>${data[i].people}</span>
            ${aa}
            </div>
            <div>
                <p>${data[i].pingjia}</p>
            </div>
        </li>
            `
        }
        $(".intro-cont1 ul").html(str)
        $('.link').html(`(${data.length}条)`)
    });
$('.ti').on("click",submitIt)
function submitIt(){
    if(getCookie("username")&&getCookie("loginsucess")=="true"){
        if($('.pingjia').val()!==''&&fen!=="0"){
            $.post('./php/comment.php',{
                id:bname,
                way:'update',
                people:getCookie("username"),
                fen:fen,
                pingjia:$('.pingjia').val()
                },function(data){
                    alert('成功提交评价')
                    location.reload();
                });
        }else{
            alert("输入内容或评分不能为空！")
        }
    }else{
        alert("只有登录后才能对商品进行评价！")
    }

}



//评价商品**************************************